import os
import sys
import time
import jwt
import pymysql

from libs.QianMysql import QianMysql
from flask import session

# 直接写死DB_CONFIG
# mysql
DB_CONFIG = {
    # 测试
    "test": {"host": "123.56.48.97", "port": 3306, "user": "hesen_23_test", "passwd": "Bn'\"I0{47.0E_Test2023", "db": "smart_lng", "charset": "utf8", "autocommit": True, "cursorclass": pymysql.cursors.DictCursor},
    # 生产
    "online": {"host": "127.0.0.1", "port": 3399, "user": "hesen_23_online", "passwd": "8.c2K1+'-4jd_Online2023", "db": "smart_lng", "charset": "utf8", "autocommit": True, "cursorclass": pymysql.cursors.DictCursor},
    "outside": {"host": "127.0.0.1", "port": 3306, "user": "hesen_23_test", "passwd": "Bn'\"I0{47.0E_Test2023", "db": "outside_cquisition", "charset": "utf8", "autocommit": True, "cursorclass": pymysql.cursors.DictCursor},
}


def check_token_expired(token):
    if token is None or token == '':
        return False
    if ',' in token:
        token = token.split(',')[0]
    try:
        tokenObj = jwt.decode(token, "k09BQnaF34Fay", 'HS256')
    except Exception as e:
        return False
    return True


def check_token_new(module_id, token):
    if token is None or token == '':
        return False
    if ',' in token:
        token = token.split(',')[0]
    try:
        tokenObj = jwt.decode(token, "k09BQnaF34Fay", 'HS256')
    except Exception as e:
        return False

    if session is None or session.get('hs-token') is None or session.get('hs-token') == '' or session.get('hs-token')!=token or tokenObj['exp'] < time.time():
        db_online = QianMysql(DB_CONFIG["online"])
        user = db_online.get_one("SELECT user_type,is_admin,real_name FROM sys_user WHERE id=%s AND del_flag=0 AND status=1", (tokenObj['id']))
        if user is None:
            return False
        # 写session
        session['hs-token'] = token
        session['user_type'] = user['user_type']
        session['is_admin'] = user['is_admin']
        session['real_name'] = user['real_name']
        session['user_id'] = tokenObj['id']
        pwoers = db_online.get_all("""
            select module_id
            from (SELECT rp.module_id as module_id,
                        ru.uid       as user_id
                from sys_role_power rp
                        LEFT JOIN sys_role_user ru on rp.role_id = ru.role_id
                WHERE rp.del_flag = 0
                    and ru.del_flag = 0
                UNION ALL
                select module_id,
                        user_id
                from sys_user_power) t
            where t.user_id = %s group by module_id
        """, (tokenObj['id']))
        session['pwoers'] = ','.join(str(item['module_id']) for item in pwoers)
        # 获取客户数据权限
        customer_pwoers = db_online.get_all("select customer_id from sys_customer_datascope where user_id=%s and del_flag=0", (tokenObj['id']))
        session['customer_pwoers'] = ','.join(str(item['customer_id']) for item in customer_pwoers) if customer_pwoers is not None and len(customer_pwoers)>0 else None
        session.permanent = True

    # 判断默认权限与管理员权限
    if session.get('user_type') == 1 and (session.get('is_admin') == 1):
        return True
    # 判断module权限
    if str(module_id) in session.get('pwoers').split(','):
        return True
    return False


def check_token_type(type, token):
    # if type == 0:
    #     # 自定义报表
    #     return check_token_new(1901, token)
    # elif type == 1:
    #     # 周报表
    #     return check_token_new(1902, token)
    if type == 2:
        # 月报表
        return check_token_new(1903, token)
    # elif type == 3:
    #     # 季度报表
    #     return check_token_new(1904, token)
    # elif type == 4:
    #     # 年度报表
    #     return check_token_new(1905, token)
    elif type == 5:
        # 气站报表
        return check_token_new(1906, token)
    elif type == 9:
        # 站点规划,地图查找站点
        return check_token_new(103015, token)
    elif type == 10:
        # 客户定价规则查看
        return check_token_new(201097, token)
    elif type == 11:
        # 客户主体利润报表
        return check_token_new(7000015, token)
    elif type == 12:
        # 客户主体利润报表-业务
        return check_token_new(7000017, token)
    elif type == 13:
        # 客户单日利润报表-业务
        return check_token_new(7000018, token)
    elif type == 14:
        # 实验室 - 对账文件对账
        return check_token_new(106011, token)
    elif type == -1:
        return check_token_expired(token)
    else:
        return False
